﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Threading;
using Wwtfly.BBS.BackModels.Models.Users;
using Wwtfly.BBS.BackModels.Models.Users.BBSPortalIdentity;

namespace Wwtfly.BBS.ForeApplication
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {

        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MvcApplication));


        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //分页路由
            routes.MapRoute(
              "Page1", // 路由名称
              "{controller}/Index/{pageParams}.html",
              new { action="Index" } // 分页大小
        );

            //分页路由2
            routes.MapRoute(
              "Page2", // 路由名称
              "{controller}/List/{pageParams}.html",
              new { action = "List" } // 分页大小
        );

            routes.MapRoute(
              "Default3", // 路由名称
              "{controller}/{action}/{id}.html",
              new {  action = "Update" } // 参数默认值
          );


            routes.MapRoute(
               "Default2", // 路由名称
               "{controller}/{action}.html",
               new { controller = "Home", action = "Index" } // 参数默认值
           );

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

        }

        protected void Application_Start()
        {
             ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new SkinEngine());
            RegisterRoutes(RouteTable.Routes);

            log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath(".") + "/log4net.config"));

        }


        // 替换当前用户
        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            BBSPortalIdentity bbsIdentity = new BBSPortalIdentity(app.Context.User.Identity, null);
            UsersModel userModel = new UsersModel();
            userModel.UserName = app.Context.User.Identity.Name;

            bbsIdentity.SetCurrentUser(userModel);
            app.Context.User = bbsIdentity;
            Thread.CurrentPrincipal = bbsIdentity;
        }
    }

    /// <summary>
    /// 自定义视图, 配合 Attribute 支持多级目录
    /// </summary>
    public class SkinEngine : WebFormViewEngine
    {
        private string[] masterLocationFormats;
        private string[] areaMasterLocationFormats;
        private string[] viewLocationFormats;
        private string[] areaViewLocationFormats;
        public SkinEngine()
        {

            masterLocationFormats = new[] {
                "~/Views/{2}/{1}/{0}.master",
                "~/Views/Shared/{0}.master"
            };

            areaMasterLocationFormats = new[] {
                "~/Areas/{2}/Views/{1}/{0}.master",
                "~/Areas/{2}/Views/Shared/{0}.master",
            };

            viewLocationFormats = new[] {
                "~/Views/{2}/{1}/{0}.aspx",
                "~/Views/{2}/{1}/{0}.ascx",
                //"~/Views/{1}/{0}.aspx",
                //"~/Views/{1}/{0}.ascx",
                "~/Views/{2}/Shared/{0}.aspx",
                "~/Views/{2}/Shared/{0}.ascx",
                "~/Views/Shared/{0}.aspx",
                "~/Views/Shared/{0}.ascx",
                
                "~/Views/Fore/Shared/{0}.aspx",
                "~/Views/Fore/Shared/{0}.ascx",
                 "~/Views/Fore/{1}/{0}.ascx",
                "~/Views/Fore/{1}/{0}.aspx",
                "~/Views/Back/Shared/{0}.aspx",
                "~/Views/Back/BackHome/{0}.aspx",
                "~/Views/Back/Shared/{0}.ascx"
            };

            areaViewLocationFormats = new[] {
                "~/Areas/{2}/Views/{1}/{0}.aspx",
                "~/Areas/{2}/Views/{1}/{0}.ascx",
                "~/Areas/{2}/Views/Shared/{0}.aspx",
                "~/Areas/{2}/Views/Shared/{0}.ascx",
            };
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            MasterLocationFormats = Brand(controllerContext, masterLocationFormats);
            AreaMasterLocationFormats = Brand(controllerContext, areaMasterLocationFormats);
            ViewLocationFormats = Brand(controllerContext, viewLocationFormats);
            AreaViewLocationFormats = Brand(controllerContext, areaViewLocationFormats);
            return base.FindView(controllerContext, viewName, masterName, useCache);
        }

        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            PartialViewLocationFormats = Brand(controllerContext, viewLocationFormats);
            AreaPartialViewLocationFormats = Brand(controllerContext, areaViewLocationFormats);
            return base.FindPartialView(controllerContext, partialViewName, useCache);
        }

        private string[] Brand(ControllerContext controllerContext, string[] locationFormats)
        {
            object folder;
            string[] formats = new string[locationFormats.Length];
            for (int i = 0; i < formats.Length; i++)
            {
                formats[i] = locationFormats[i].Replace("{2}",
                    controllerContext.RouteData.DataTokens.TryGetValue("__View__Folder", out folder)
                        ? folder.ToString()
                        : string.Empty);
            }
            return formats;
        }
    }
}